//
//  AppDelegate.m
//  YiBaoStore
//
//  Created by 毛云河 on 2018/10/1.
//  Copyright © 2018年 小河. All rights reserved.
//

#import "AppDelegate.h"
#import <WXApi.h>
#import "WXApiManager.h"
#import <AlipaySDK/AlipaySDK.h>
#import <JPUSHService.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import "LoginController.h"
#import "CreateAccountController.h"
#import "MaintainViewController.h"
#import "ADDNewShopViewController.h"
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

@interface AppDelegate ()<JPUSHRegisterDelegate,AVSpeechSynthesizerDelegate>
{
    UIBackgroundTaskIdentifier _bgTaskId;
    AVAudioPlayer *player;
}
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    [self setRootViewController];
    
    //注册高德地图key
    [AMapServices sharedServices].apiKey = @"7e1bf0068d7d2a6434588dda693580d3";
    //1.向微信注册
    [WXApi registerApp:WEXIN_KEY enableMTA:NO];
    //注册bugly
    [Bugly startWithAppId:@"05b6f9e18d"];
    //初始化极光推送
    [self initJPush:launchOptions];
    //注册友盟
    [self initUMSocial];
    return YES;
}

//注册友盟
- (void)initUMSocial
{
    /* 设置友盟appkey */
    //打开调试
    [[UMSocialManager defaultManager] openLog:YES];
    [[UMSocialManager defaultManager] setUmSocialAppkey:UMengKey];
    //[UMConfigure initWithAppkey:UMengKey channel:nil];
    [self configUSharePlatforms];
}

#pragma mark - 配置友盟分享微信信息
- (void)configUSharePlatforms
{
    /* 设置微信的appKey和appSecret */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:WEXIN_KEY appSecret:WEXIN_SECRET redirectURL:@"http://mobile.umeng.com/social"];
}

- (void)setRootViewController
{
    NSString *loginStatue = USER_DEFAULTS_GET(LoginStatue);
    //NSString *stepStatue = nil;
    //NSString *storeState = USER_DEFAULTS_GET(StoreStatue);
    LoginController *login = [[LoginController alloc]init];
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:login];
    if ([TTKUtil isNil:loginStatue])
    {
        self.window.rootViewController = nav;
    }
    else
    {
        __weak __typeof(self) weakSelf = self;
        [HttpRequest formPostPath:ShopState_API params:nil resultBlock:^(id Data, MsgModel *msgModel)
         {
             //session失效
             if (msgModel.status == 401) {
                 self.window.rootViewController = nav;
             }
             else if (msgModel.status == 404) {//未注册店铺
                 weakSelf.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:[ADDNewShopViewController new]];
             }
             else if (msgModel.status == 200)
             {
                 self.storeState = Data[@"result"];
                 self.stepStatue = Data[@"attributes"][@"shopRegisterStep"];
                 dispatch_async(dispatch_get_main_queue(), ^{
                     if ([self.storeState integerValue]==0)
                     {
                         if ([self.stepStatue integerValue] == 100 || [self.stepStatue integerValue] == 105) //通联未绑定
                         {
                             //创建通联会员
                             CreateAccountController *createVC = [CreateAccountController new];
                             weakSelf.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:createVC];
                         }
                         else if([self.stepStatue integerValue]==110||[self.stepStatue integerValue]==115||[self.stepStatue integerValue]==116) //银行卡未绑定
                         {
                             //绑定银行卡
                             MaintainViewController *bankCodeVC = [MaintainViewController new];
                             self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:bankCodeVC];
                         }
                         else if([self.stepStatue integerValue] == 120)//没有点击确定按钮
                         {
                             BasicWebViewController *basicVC = [BasicWebViewController new];
                             dispatch_async(dispatch_get_main_queue(), ^{
                                 [HttpRequest formPostPath:GetSignUrl_API params:nil resultBlock:^(id Data, MsgModel *msgModel)
                                  {
                                      dispatch_async(dispatch_get_main_queue(), ^{
                                          basicVC.url = Data[@"result"];
                                          self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:basicVC];
                                      });
                                  }];
                             });
                         }
                     }
                     else if ([self.storeState integerValue]==10)
                     {
                         //待签约
                         CheckShopViewController *checkVC = [CheckShopViewController new];
                         self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:checkVC];
                     }
                     else if ([self.storeState integerValue] == 1)
                     {
                         //注册完成
                         MYHTabBarController *tab = [MYHTabBarController new];
                         AppDelegate* app = (AppDelegate *)[UIApplication sharedApplication].delegate;
                         app.window.rootViewController = tab;
                     }
                     else if ([self.storeState integerValue] == -10)
                     {
                         ADDNewShopViewController *addNew = [ADDNewShopViewController new];
                         addNew.isFailure = YES;
                         weakSelf.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:addNew];
                     }
                     else
                     {
                         self.window.rootViewController = nav;
                     }
                     
                 });
             }
             else if (msgModel.status == -1)
             {
                 self.window.rootViewController = nav;
             }
             else
             {
                 self.window.rootViewController = nav;
             }
             
         }];
    }
    //    MYHTabBarController *tab = [MYHTabBarController new];
    //    AppDelegate* app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    //    app.window.rootViewController = tab;
    //    [self.window makeKeyAndVisible];
}

#pragma mark --支付回调
//iOS9 以后的新方法  （9.0以后使用新API接口）
- (BOOL)application:(UIApplication *)app
            openURL:(NSURL *)url
            options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
{
    BOOL result = [[UMSocialManager defaultManager]  handleOpenURL:url options:options];
    if (!result) {
        // 其他如支付等SDK的回调
        //支付宝支付
        __weak __typeof(self) weakSelf = self;
        if ([url.host isEqualToString:@"safepay"]) {
            [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
                //利用代理监听支付宝回调，通知会出现支付和充值回调混乱
                //            if (_alipayDelegate && [_alipayDelegate respondsToSelector:@selector(getAlipayPayResult:)]) {
                //                [_alipayDelegate getAlipayPayResult:resultDic];
                //            }
                //充值回调
                if (weakSelf.alipayRechargeDelegate && [weakSelf.alipayRechargeDelegate respondsToSelector:@selector(getAlipayRechargeResult:)]){
                    [weakSelf.alipayRechargeDelegate getAlipayRechargeResult:resultDic];
                }
            }];
            return YES;
        }
        //微信支付
        else{
            return [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
        }
    }
    return result;
}

//iOS9之前
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    //IOS9以前
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
    if (!result)
    {
        __weak __typeof(self) weakSelf = self;
        if ([url.host isEqualToString:@"safepay"]) {
            [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
                //            //利用代理监听支付宝回调，通知会出现支付和充值回调混乱
                //            if (weakSelf.alipayDelegate && [weakSelf.alipayDelegate respondsToSelector:@selector(getAlipayPayResult:)]) {
                //                [weakSelf.alipayDelegate getAlipayPayResult:resultDic];
                //            }
                //充值回调
                if (weakSelf.alipayRechargeDelegate && [weakSelf.alipayRechargeDelegate respondsToSelector:@selector(getAlipayRechargeResult:)]){
                    [weakSelf.alipayRechargeDelegate getAlipayRechargeResult:resultDic];
                }
            }];
            return YES;
        }
        else{
            return [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
        }
    }
    
    return result;
}

//- (BOOL)application:(UIApplication *)app
//            openURL:(NSURL *)url
//            options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
//{
//    //6.3的新的API调用，是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响
//    BOOL result = [[UMSocialManager defaultManager]  handleOpenURL:url options:options];
//    if (!result) {
//        // 其他如支付等SDK的回调
//    }
//    return result;
//}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    return result;
}

#pragma mark - 小程序回调
-(void)onResp:(BaseResp *)resp
{
    if ([resp isKindOfClass:[WXLaunchMiniProgramResp class]])
    {
        //        NSString *string = resp.extMsg;
        // 对应JsApi navigateBackApplication中的extraData字段数据
    }
}

#pragma mark -- 极光推送
- (void)initJPush:(NSDictionary *)launchOptions  {
    //Required
    //notice: 3.0.0及以后版本注册可以这样写，也可以继续用之前的注册方式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    if (@available(iOS 12.0, *)) {
        entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound|JPAuthorizationOptionProvidesAppNotificationSettings;
    } else {
        entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    }
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0)
    {
        JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
        entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionSound;
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    }else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0)
    {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    }
    //if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
    // 可以添加自定义categories
    // NSSet<UNNotificationCategory *> *categories for iOS10 or later
    // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    //}
    
    [[UIApplication sharedApplication] registerForRemoteNotifications];
    //[JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            NSLog(@"registrationID获取成功：%@",registrationID);
        }
        else{
            NSLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
    
    //YES 生产环境  No 测试环境
    [JPUSHService setupWithOption:launchOptions appKey:JPushKey channel:@"Publish channel" apsForProduction:YES advertisingIdentifier:nil];
}

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
    NSLog(@"注册deviceToken");
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

//iOS12 support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification
{
    NSDictionary * userInfo = notification.request.content.userInfo;
    if (notification && [notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        //从通知界面直接进入应用
    }else{
        //从通知设置界面进入应用
        [JPUSHService handleRemoteNotification:userInfo];
    }
    [self dealWithPushMsg:userInfo with:3];
}


// iOS 10 Support 前台接受消息
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    else
    {
        NSLog(@"本地推送");
    }
    completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert|UNNotificationPresentationOptionBadge); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
    //处理推送的消息
    [self dealWithPushMsg:userInfo with:1];
}

// iOS 10 Support  后台接受消息
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary *userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
    
    [self dealWithPushMsg:userInfo with:2];
}

///Required, iOS 7 Support
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
    //判断ios10之前或者iOS12.1之后
    if (lowIos10x || ([[[UIDevice currentDevice] systemVersion] compare:@"12.1" options:NSNumericSearch] != NSOrderedAscending)) {
        [self dealWithPushMsg:userInfo with:2];
    }
    else
    {
        [self dealWithPushMsg:userInfo with:2];
    }
}

//Required, iOS 6 Support
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required, For systems with less than or equal to iOS 6
    [JPUSHService handleRemoteNotification:userInfo];
    [self dealWithPushMsg:userInfo with:2];
}

#pragma mark -- 处理推送消息
- (void)dealWithPushMsg:(NSDictionary *)userInfo with:(int)index
{
    if (![TTKUtil isOpenNotify]) {
        return;
    }
    NSLog(@"userinfo = %@",userInfo);
    BOOL isNeedSpeech = [[userInfo objectForKey:@"withSpeech"] boolValue];
    NSDictionary *dict = [userInfo objectForKey:@"aps"];
    NSString *content = [dict objectForKey:@"alert"];
    if (isNeedSpeech)
    {
        AVSpeechSynthesizer *synthesizer = [[AVSpeechSynthesizer alloc] init];
        AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc] initWithString:[NSString stringWithFormat:@"%@",content]];
        synthesizer.delegate = self;
        //音量
        utterance.volume = 1.0f;
        utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"]; //设置使用什么语言播放
        utterance.rate = 0.5f; //设置语音内容的速度 （0-1）
        utterance.pitchMultiplier = 1.0f; //声音的音调0.5f~2.0f
        // utterance.postUtteranceDelay = 0.1; //目的是让语音合成器播放下一语句前又短暂的暂停
        //上一句之前需要多久
        //utterance.preUtteranceDelay = 0.5f;
        [synthesizer speakUtterance:utterance];
    }
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    [JPUSHService setBadge:0];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive stat
    NSLog(@"后台..");
//    //开启后台处理多媒体事件
//    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
//    AVAudioSession *session=[AVAudioSession sharedInstance];
//    [session setActive:YES error:nil];
//    //后台播放
//    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
//    //这样做，可以在按home键进入后台后 ，播放一段时间，几分钟吧。但是不能持续播放网络歌曲，若需要持续播放网络歌曲，还需要申请后台任务id，具体做法是：
//    _bgTaskId= [AppDelegate backgroundPlayerID:_bgTaskId];
//    //其中的_bgTaskId是后台任务UIBackgroundTaskIdentifier _bgTaskId;
//    //后台播放无声音乐
//    NSString *musicPath = [[NSBundle mainBundle] pathForResource:@"wusheng" ofType:@"mp3"];
//    NSURL *myUrl = [[NSURL alloc] initFileURLWithPath:musicPath];
//    // 创建播放器
//    if (player == nil) {
//        player = [[AVAudioPlayer alloc] initWithContentsOfURL:myUrl error:nil];
//        [player prepareToPlay];
//        [player setVolume:1.0];
//        player.numberOfLoops = -1; //设置音乐播放次数  -1为一直循环
//        [player play]; //播放
//    }
}

+(UIBackgroundTaskIdentifier)backgroundPlayerID:(UIBackgroundTaskIdentifier)backTaskId
{
    //设置并激活音频会话类别
    AVAudioSession *session=[AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    [session setActive:YES error:nil];
    //允许应用程序接收远程控制
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    //设置后台任务ID
    UIBackgroundTaskIdentifier newTaskId=UIBackgroundTaskInvalid;
    newTaskId=[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
    if(newTaskId!=UIBackgroundTaskInvalid&&backTaskId!=UIBackgroundTaskInvalid)
    {
        [[UIApplication sharedApplication] endBackgroundTask:backTaskId];
    }
    return newTaskId;
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
